//
//  ChangeGestureViewController.m
//  ZYZB
//
//  Created by ENERGY on 2018/7/30.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "ChangeGestureViewController.h"
#import "ZLGestureLockView.h"
#import "ZLGestureLockIndicator.h"

#define GesturesPassword @"gesturespassword"

@interface ChangeGestureViewController ()<ZLGestureLockDelegate, UIAlertViewDelegate, UINavigationControllerDelegate>
@property (strong, nonatomic) ZLGestureLockView *gestureLockView;
@property (strong, nonatomic) ZLGestureLockIndicator *gestureLockIndicator;
// 手势状态栏提示label
@property (weak, nonatomic) UILabel *statusLabel;
// 请输入原手势密码
@property (weak, nonatomic) UILabel *subTitleLabel;
// 账户名
@property (weak, nonatomic) UILabel *nameLabel;
// 账户头像
@property (weak, nonatomic) UIImageView *headIcon;
// 其他账户登录按钮
@property (weak, nonatomic) UIButton *otherAcountBtn;
// 重新绘制按钮
@property (weak, nonatomic) UIButton *resetPswBtn;
// 忘记手势密码按钮
@property (weak, nonatomic) UIButton *forgetPswBtn;
// 创建的手势密码
@property (nonatomic, copy) NSString *lastGesturePsw;
@property (nonatomic) ZLUnlockType unlockType;
@property (nonatomic, strong)UIImageView * iconImgView;
@end

@implementation ChangeGestureViewController
#pragma mark - 类方法
+ (void)deleteGesturesPassword {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:GesturesPassword];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
+ (void)addGesturesPassword:(NSString *)gesturesPassword {
    [[NSUserDefaults standardUserDefaults] setObject:gesturesPassword forKey:GesturesPassword];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
+ (NSString *)gesturesPassword {
    return [[NSUserDefaults standardUserDefaults] objectForKey:GesturesPassword];
}
#pragma mark - inint
- (instancetype)initWithUnlockType:(ZLUnlockType)unlockType {
    if (self = [super init]) {
        _unlockType = unlockType;
    }
    return self;
}
#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    BOOL isHomePage = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isHomePage animated:YES];
}
#pragma mark - viewDidLoad
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.delegate = self;
    [self setStatusBarBackgroundColor:[UIColor whiteColor]];
}
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupMainUI];
    self.gestureLockView.delegate = self;
    
    self.resetPswBtn.hidden = YES;
    switch (_unlockType) {
        case ZLUnlockTypeCreatePsw:
        {
            self.gestureLockIndicator.hidden = NO;
            self.subTitleLabel.text = @"绘制解锁图案";
            self.statusLabel.text = @"";
            self.otherAcountBtn.hidden = self.forgetPswBtn.hidden = self.nameLabel.hidden = self.headIcon.hidden = YES;
        }
            break;
        case ZLUnlockTypeValidatePsw:
        {
            self.gestureLockIndicator.hidden = YES;
            self.subTitleLabel.text = @"请输入原手势密码";
            self.otherAcountBtn.hidden = self.forgetPswBtn.hidden = self.nameLabel.hidden = self.headIcon.hidden = NO;

        }
            break;
        default:
            break;
    }
    //左上角×
    UIImageView * closeImg = [[UIImageView alloc] init];
    int iconW = 150/WIDTH_6_SCALE;
    if (Is_Iphone_X) {
        self.iconImgView.frame = CGRectMake((SCREEN_WIDTH - iconW)/2, 60/WIDTH_6_SCALE + 24, iconW, 43.5/WIDTH_6_SCALE);
        closeImg.frame = CGRectMake(18/WIDTH_6_SCALE, 34/WIDTH_6_SCALE + 24, 15/WIDTH_6_SCALE, 15/WIDTH_6_SCALE);
    }else{
        self.iconImgView.frame = CGRectMake((SCREEN_WIDTH - iconW)/2, 60/WIDTH_6_SCALE, iconW, 43.5/WIDTH_6_SCALE);
        closeImg.frame = CGRectMake(18/WIDTH_6_SCALE, 34/WIDTH_6_SCALE, 15/WIDTH_6_SCALE, 15/WIDTH_6_SCALE);
    }
    self.iconImgView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.iconImgView];
    closeImg.backgroundColor = [UIColor blackColor];
    [self.view addSubview:closeImg];
    UIButton * coverCloseBtn = [[UIButton alloc] initWithFrame:CGRectMake(closeImg.left - 14/WIDTH_6_SCALE, closeImg.top - 14/WIDTH_6_SCALE, closeImg.width + 28/WIDTH_6_SCALE, closeImg.width + 28/WIDTH_6_SCALE)];
    [coverCloseBtn setBackgroundColor:[UIColor orangeColor]];
    [self.view addSubview:coverCloseBtn];
    [coverCloseBtn addTarget:self action:@selector(closeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}
// 创建界面
- (void)setupMainUI {
    // 账户名
    UILabel *nameLabel = [[UILabel alloc]init];
    if (Is_Iphone_X) {
        nameLabel.frame = CGRectMake(0, 10/WIDTH_6_SCALE, SCREEN_WIDTH + 88/WIDTH_6_SCALE, 15/WIDTH_6_SCALE);
    }else{
        nameLabel.frame = CGRectMake(0, 10/WIDTH_6_SCALE + 64/WIDTH_6_SCALE, SCREEN_WIDTH, 15/WIDTH_6_SCALE);
    }
    nameLabel.textAlignment = NSTextAlignmentCenter;
    nameLabel.text = @"设置手势密码";
    nameLabel.font = [UIFont systemFontOfSize:16];
    nameLabel.textColor = [UIColor blackColor];
    [self.view addSubview:nameLabel];
    //二级标题
    UILabel *subTitleLabel = [[UILabel alloc]init];
    subTitleLabel.frame = CGRectMake(0, nameLabel.bottom + 22/WIDTH_6_SCALE, SCREEN_WIDTH, 13/WIDTH_6_SCALE);
    subTitleLabel.textAlignment = NSTextAlignmentCenter;
    subTitleLabel.text = @"请输入原手势密码";
    subTitleLabel.font = [UIFont systemFontOfSize:13];
    subTitleLabel.textColor = [UIColor blackColor];
    [self.view addSubview:subTitleLabel];
    
    // 手势状态栏提示label
    UILabel *statusLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, subTitleLabel.bottom + 22/WIDTH_6_SCALE, SCREEN_WIDTH, 14/WIDTH_6_SCALE)];
    statusLabel.textAlignment = NSTextAlignmentCenter;
    statusLabel.text = @"验证手势密码";
    statusLabel.font = [UIFont systemFontOfSize:14];
    statusLabel.textColor = getColor(@"ff4433");
    [self.view addSubview:statusLabel];
    self.statusLabel = statusLabel;
    
    // 九宫格 手势密码页面
    ZLGestureLockView *gestureLockView = [[ZLGestureLockView alloc]initWithFrame:CGRectMake(0, statusLabel.bottom + 72/WIDTH_6_SCALE, self.view.frame.size.width, self.view.frame.size.width)];
    gestureLockView.delegate = self;
    [self.view addSubview:gestureLockView];
    self.gestureLockView = gestureLockView;
}
#pragma mark - private
//  创建手势密码
- (void)createGesturesPassword:(NSMutableString *)gesturesPassword {
    if (self.lastGesturePsw.length == 0) {
        if (gesturesPassword.length < 4) {
            self.statusLabel.text = @"至少连接四个点，请重新输入";
            [self shakeAnimationForView:self.statusLabel];
            return;
        }
        if (self.resetPswBtn.hidden == YES) {
            self.resetPswBtn.hidden = NO;
        }
        self.lastGesturePsw = gesturesPassword;
        [self.gestureLockIndicator setGesturePassword:gesturesPassword];
        self.statusLabel.text = @"请再次绘制手势密码";
        return;
    }
    if ([self.lastGesturePsw isEqualToString:gesturesPassword]) { // 绘制成功
        [self dismissViewControllerAnimated:YES completion:^{
            // 保存手势密码
            [ChangeGestureViewController addGesturesPassword:gesturesPassword];
        }];
    }else {
        self.statusLabel.text = @"与上一次绘制不一致，请重新绘制";
        [self shakeAnimationForView:self.statusLabel];
    }
}
// 验证手势密码
- (void)validateGesturesPassword:(NSMutableString *)gesturesPassword {
    static NSInteger errorCount = 5;
    if ([gesturesPassword isEqualToString:[ChangeGestureViewController gesturesPassword]]) {
        errorCount = 5;
        ChangeGestureViewController * vc = [[ChangeGestureViewController alloc] initWithUnlockType:ZLUnlockTypeCreatePsw];
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        if (errorCount - 1 == 0) { // 你已经输错五次了！ 退出重新登陆！
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"手势密码已失效" message:@"请重新登陆" delegate:self cancelButtonTitle:nil otherButtonTitles:@"重新登陆", nil];
            [alertView show];
            errorCount = 5;
            return;
        }
        self.statusLabel.text = [NSString stringWithFormat:@"密码错误，还可以再输入%ld次",--errorCount];
        [self shakeAnimationForView:self.statusLabel];
    }
}
// 抖动动画
- (void)shakeAnimationForView:(UIView *)view {
    CALayer *viewLayer = view.layer;
    CGPoint position = viewLayer.position;
    CGPoint left = CGPointMake(position.x - 10, position.y);
    CGPoint right = CGPointMake(position.x + 10, position.y);
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [animation setFromValue:[NSValue valueWithCGPoint:left]];
    [animation setToValue:[NSValue valueWithCGPoint:right]];
    [animation setAutoreverses:YES]; // 平滑结束
    [animation setDuration:0.08];
    [animation setRepeatCount:3];
    
    [viewLayer addAnimation:animation forKey:nil];
}
#pragma mark - 按钮点击事件 Anction
- (void)closeBtnClick:(UIButton *)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}
// 点击其他账号登陆按钮
- (void)otherAccountLogin:(id)sender {
    NSLog(@"%s",__FUNCTION__);
}
// 点击忘记手势密码按钮
- (void)forgetGesturesPassword:(id)sender {
    NSLog(@"%s",__FUNCTION__);
}
#pragma mark - ZLgestureLockViewDelegate
- (void)gestureLockView:(ZLGestureLockView *)lockView drawRectFinished:(NSMutableString *)gesturePassword {
    switch (_unlockType) {
        case ZLUnlockTypeCreatePsw: // 创建手势密码
        {
            [self createGesturesPassword:gesturePassword];
        }
            break;
        case ZLUnlockTypeValidatePsw: // 校验手势密码
        {
            [self validateGesturesPassword:gesturePassword];
        }
            break;
        default:
            break;
    }
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    // 重新登陆
    NSLog(@"重新登陆");
    //网络接口，判断是否够十分钟，十分钟过后才可以重新输入原手机密码
}

@end
